const express = require('express');
const router = express.Router();
const { Setting } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { NotFound } = require('http-errors');
const { delKey } = require('../../utils/redis');

/**
 * 公共方法：白名单过滤
 * @param req
 * @returns {{copyright: (string|*), icp: (string|string|DocumentFragment|*), name}}
 */
const filterBody = (req) => {
  return {
    name: req.body.name,
    icp: req.body.icp,
    copyright: req.body.copyright,
  };
};

/**
 * 公共方法：查询当前系统设置
 */
const getSetting = async () => {
  const setting = await Setting.findOne();
  if (!setting) {
    throw new NotFound('初始系统设置未找到，请运行种子文件。');
  }
  return setting;
};

/**
 * 查询系统设置详情
 * GET /admin/settings/
 */
router.get('/', async (req, res) => {
  try {
    // 查询数据
    const setting = await getSetting();
    success(res, '查询系统设置详情成功', { data: setting });
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 更新系统设置
 * PUT /admin/settings/
 */
router.put('/', async (req, res) => {
  try {
    const setting = await getSetting();
    // 更新系统设置
    const updateSetting = await setting.update(filterBody(req));

    // 删除缓存
    await delKey('setting');
    success(res, '更新系统设置成功', { data: updateSetting });
  } catch (error) {
    failure(res, error);
  }
});

module.exports = router;
